parameters:
  # Which publishing infra should be used. THIS SHOULD MATCH THE VERSION ON THE BUILD MANIFEST.
  # Publishing V1 is no longer supported
  # Publishing V2 is no longer supported
  # Publishing V3 is the default
  - name: publishingInfraVersion
    displayName: Which version of publishing should be used to promote the build definition?
    type: number
    default: 3
    values:
    - 3

  - name: BARBuildId
    displayName: BAR Build Id
    type: number
    default: 0

  - name: PromoteToChannelIds
    displayName: Channel to promote BARBuildId to
    type: string
    default: ''

  - name: enableSourceLinkValidation
    displayName: Enable SourceLink validation
    type: boolean
    default: false

  - name: enableSigningValidation
    displayName: Enable signing validation
    type: boolean
    default: true

  - name: enableSymbolValidation
    displayName: Enable symbol validation
    type: boolean
    default: false

  - name: enableNugetValidation
    displayName: Enable NuGet validation
    type: boolean
    default: true

  - name: publishInstallersAndChecksums
    displayName: Publish installers and checksums
    type: boolean
    default: true

  - name: SDLValidationParameters
    type: object
    default:
      enable: false
      publishGdn: false
      continueOnError: false
      params: ''
      artifactNames: ''
      downloadArtifacts: true

  # These parameters let the user customize the call to sdk-task.ps1 for publishing
  # symbols & general artifacts as well as for signing validation
  - name: symbolPublishingAdditionalParameters
    displayName: Symbol publishing additional parameters
    type: string
    default: ''

  - name: artifactsPublishingAdditionalParameters
    displayName: Artifact publishing additional parameters
    type: string
    default: ''

  - name: signingValidationAdditionalParameters
    displayName: Signing validation additional parameters
    type: string
    default: ''

  # Which stages should finish execution before post-build stages start
  - name: validateDependsOn
    type: object
    default:
    - build

  - name: publishDependsOn
    type: object
    default:
    - Validate

  # Optional: Call asset publishing rather than running in a separate stage
  - name: publishAssetsImmediately
    type: boolean
    default: false

stages:
- ${{ if or(eq( parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}:
  - stage: Validate
    dependsOn: ${{ parameters.validateDependsOn }}
    displayName: Validate Build Assets
    variables:
      - template: common-variables.yml
      - template: /eng/common/templates/variables/pool-providers.yml
    jobs:
    - job:
      displayName: NuGet Validation
      condition: and(succeededOrFailed(), eq( ${{ parameters.enableNugetValidation }}, 'true'))
      pool:
        # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com)
        ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}:
          name: VSEngSS-MicroBuild2022-1ES
          demands: Cmd
        # If it's not devdiv, it's dnceng
        ${{ else }}:
          name: $(DncEngInternalBuildPool)
          demands: ImageOverride -equals windows.vs2019.amd64

      steps:
        - template: setup-maestro-vars.yml
          parameters:
            BARBuildId: ${{ parameters.BARBuildId }}
            PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }}

        - task: DownloadBuildArtifacts@0
          displayName: Download Package Artifacts
          inputs:
            buildType: specific
            buildVersionToDownload: specific
            project: $(AzDOProjectName)
            pipeline: $(AzDOPipelineId)
            buildId: $(AzDOBuildId)
            artifactName: PackageArtifacts
            checkDownloadedFiles: true

        - task: PowerShell@2
          displayName: Validate
          inputs:
            filePath: $(Build.SourcesDirectory)/eng/common/post-build/nuget-validation.ps1
            arguments: -PackagesPath $(Build.ArtifactStagingDirectory)/PackageArtifacts/
              -ToolDestinationPath $(Agent.BuildDirectory)/Extract/

    - job:
      displayName: Signing Validation
      condition: and( eq( ${{ parameters.enableSigningValidation }}, 'true'), ne( variables['PostBuildSign'], 'true'))
      pool:
        # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com)
        ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}:
          name: VSEngSS-MicroBuild2022-1ES
          demands: Cmd
        # If it's not devdiv, it's dnceng
        ${{ else }}:
          name: $(DncEngInternalBuildPool)
          demands: ImageOverride -equals windows.vs2019.amd64
      steps:
        - template: setup-maestro-vars.yml
          parameters:
            BARBuildId: ${{ parameters.BARBuildId }}
            PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }}

        - task: DownloadBuildArtifacts@0
          displayName: Download Package Artifacts
          inputs:
            buildType: specific
            buildVersionToDownload: specific
            project: $(AzDOProjectName)
            pipeline: $(AzDOPipelineId)
            buildId: $(AzDOBuildId)
            artifactName: PackageArtifacts
            checkDownloadedFiles: true
            itemPattern: |
              **
              !**/Microsoft.SourceBuild.Intermediate.*.nupkg

        # This is necessary whenever we want to publish/restore to an AzDO private feed
        # Since sdk-task.ps1 tries to restore packages we need to do this authentication here
        # otherwise it'll complain about accessing a private feed.
        - task: NuGetAuthenticate@1
          displayName: 'Authenticate to AzDO Feeds'

        # Signing validation will optionally work with the buildmanifest file which is downloaded from
        # Azure DevOps above.
        - task: PowerShell@2
          displayName: Validate
          inputs:
            filePath: eng\common\sdk-task.ps1
            arguments: -task SigningValidation -restore -msbuildEngine vs
              /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts'
              /p:SignCheckExclusionsFile='$(Build.SourcesDirectory)/eng/SignCheckExclusionsFile.txt'
              ${{ parameters.signingValidationAdditionalParameters }}

        - template: ../steps/publish-logs.yml
          parameters:
            StageLabel: 'Validation'
            JobLabel: 'Signing'
            BinlogToolVersion: $(BinlogToolVersion)

    - job:
      displayName: SourceLink Validation
      condition: eq( ${{ parameters.enableSourceLinkValidation }}, 'true')
      pool:
        # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com)
        ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}:
          name: VSEngSS-MicroBuild2022-1ES
          demands: Cmd
        # If it's not devdiv, it's dnceng
        ${{ else }}:
          name: $(DncEngInternalBuildPool)
          demands: ImageOverride -equals windows.vs2019.amd64
      steps:
        - template: setup-maestro-vars.yml
          parameters:
            BARBuildId: ${{ parameters.BARBuildId }}
            PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }}

        - task: DownloadBuildArtifacts@0
          displayName: Download Blob Artifacts
          inputs:
            buildType: specific
            buildVersionToDownload: specific
            project: $(AzDOProjectName)
            pipeline: $(AzDOPipelineId)
            buildId: $(AzDOBuildId)
            artifactName: BlobArtifacts
            checkDownloadedFiles: true

        - task: PowerShell@2
          displayName: Validate
          inputs:
            filePath: $(Build.SourcesDirectory)/eng/common/post-build/sourcelink-validation.ps1
            arguments: -InputPath $(Build.ArtifactStagingDirectory)/BlobArtifacts/
              -ExtractPath $(Agent.BuildDirectory)/Extract/
              -GHRepoName $(Build.Repository.Name)
              -GHCommit $(Build.SourceVersion)
              -SourcelinkCliVersion $(SourceLinkCLIVersion)
          continueOnError: true

    - template: /eng/common/templates/job/execute-sdl.yml
      parameters:
        enable: ${{ parameters.SDLValidationParameters.enable }}
        publishGuardianDirectoryToPipeline: ${{ parameters.SDLValidationParameters.publishGdn }}
        additionalParameters: ${{ parameters.SDLValidationParameters.params }}
        continueOnError: ${{ parameters.SDLValidationParameters.continueOnError }}
        artifactNames: ${{ parameters.SDLValidationParameters.artifactNames }}
        downloadArtifacts: ${{ parameters.SDLValidationParameters.downloadArtifacts }}

- ${{ if ne(parameters.publishAssetsImmediately, 'true') }}:
  - stage: publish_using_darc
    ${{ if or(eq(parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}:
      dependsOn: ${{ parameters.publishDependsOn }}
    ${{ else }}:
      dependsOn: ${{ parameters.validateDependsOn }}
    displayName: Publish using Darc
    variables:
      - template: common-variables.yml
      - template: /eng/common/templates/variables/pool-providers.yml
    jobs:
    - job:
      displayName: Publish Using Darc
      timeoutInMinutes: 120
      pool:
        # We don't use the collection uri here because it might vary (.visualstudio.com vs. dev.azure.com)
        ${{ if eq(variables['System.TeamProject'], 'DevDiv') }}:
          name: VSEngSS-MicroBuild2022-1ES
          demands: Cmd
        # If it's not devdiv, it's dnceng
        ${{ else }}:
          name: NetCore1ESPool-Publishing-Internal
          demands: ImageOverride -equals windows.vs2019.amd64
      steps:
        - template: setup-maestro-vars.yml
          parameters:
            BARBuildId: ${{ parameters.BARBuildId }}
            PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }}

        - task: NuGetAuthenticate@1

        - task: PowerShell@2
          displayName: Publish Using Darc
          inputs:
            filePath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1
            arguments: -BuildId $(BARBuildId)
              -PublishingInfraVersion ${{ parameters.publishingInfraVersion }}
              -AzdoToken '$(publishing-dnceng-devdiv-code-r-build-re)'
              -MaestroToken '$(MaestroApiAccessToken)'
              -WaitPublishingFinish true
              -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}'
              -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}'
